mod handler;

use crate::handler::header_to_sql;
use calamine::{Reader, Xlsx, open_workbook};
use handler::{header_to_model, header_to_variable};
use std::error::Error;
// use std::io::BufRead;

fn parse_args() -> String {
    let args = std::env::args().collect::<Vec<String>>();
    match args.get(1) {
        Some(file_path) => file_path.to_string(),
        None => "/mnt/home/cc/windows/Fee_Details_USD_20250301_20250331.xlsx已标黄fee+0.2.xlsx"
            .to_string(),
    }
}

fn parse_header(path: &str, header_row: usize) -> Result<Vec<String>, Box<dyn Error>> {
    let mut headers = Vec::new();
    // let file = std::fs::File::open(path).unwrap();
    // let reader = BufReader::new(file);
    // for line in reader.lines() {
    //     let line = line.unwrap();
    //     println!("{}", line);
    //     headers.push(line);
    // }

    let mut workbook: Xlsx<_> = open_workbook(path)?;
    let sheet_names = workbook.sheet_names();
    if let Some(sheet_name) = sheet_names.first() {
        let sheet = workbook.worksheet_range(sheet_name).unwrap();
        let header_data = sheet.rows().nth(header_row - 1).unwrap();
        headers = header_data.iter().map(|cell| cell.to_string()).collect();
        // for header in header_data {
        //     headers.push(header.to_string());
        // }
    }
    Ok(headers)
}

fn main() {
    // let args = std::env::args().collect::<Vec<_>>();
    // println!("{:#?}", args);
    //
    // let file_path = match args.get(1) {
    //     Some(file_path) => file_path,
    //     None => "/mnt/home/cc/windows/Fee_Details_USD_20250301_20250331.xlsx已标黄fee+0.2.xlsx",
    // };
    let file_path = parse_args();

    let headers = parse_header(&file_path, 1).unwrap();

    let new_headers = header_to_variable(&headers);
    let models = header_to_model(&headers);
    let sqls = header_to_sql(&headers, "airwallex_settlement_details");

    println!("{:?}", new_headers);
    println!("{:?}", headers);
    println!("{:?}", models);
    println!("{}", sqls.join("\n"));
}
